package com.android1608.administrator.encryption;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {
    private String path = "http://api.m.mtime.cn/Showtime/LocationMovies.api?locationId=%s";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //URL Encode编码

            String encode = URLEncoder.encode("%");
            path = path+encode+"s";

        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream in = null;
                ByteArrayOutputStream baos = null;
                try {
                    URL url = new URL(path);
                    //2、通过url，开通HttpUrlConnection
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //3、进行设置
                    conn.setConnectTimeout(3000);
                    //4、获取数据
                    if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
                        in = conn.getInputStream();

                        baos = new ByteArrayOutputStream();

                        byte[] buf = new byte[1024*8];

                        int len = 0;

                        while((len = in.read(buf))!=-1){
                            baos.write(buf, 0, len);
                        }

                        //5、返回数据
                        byte[] data = baos.toByteArray();

//                        return data;
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }finally{
                    if(in!=null){
                        try {
                            in.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if(baos!=null){
                        try {
                            baos.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }

            }
        }).start();
    }
}
